from typing import Dict, List, Optional
from sqlalchemy import and_
from ..models.role_permission import RolePermission
from ..models.role import Role
from ..models.permission import Permission
from ..extensions.extensions import db
from datetime import datetime, timezone

class RolePermissionService:
    @staticmethod
    def get_role_permission_list(page: int = 1, per_page: int = 10, role_id: Optional[int] = None) -> Dict:
        """
        获取角色权限关系列表
        :param page: 页码
        :param per_page: 每页数量
        :param role_id: 角色ID过滤
        :return: 角色权限关系列表和分页信息
        """
        query = RolePermission.query.filter_by(deleted=False)
        
        # 按角色ID过滤
        if role_id:
            query = query.filter(RolePermission.role_id == role_id)
        
        # 分页
        pagination = query.order_by(RolePermission.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 获取关联数据
        items = []
        for item in pagination.items:
            role = Role.query.get(item.role_id)
            permission = Permission.query.get(item.permission_id)
            if role and permission:
                data = item.to_dict()
                data.update({
                    'role_name': role.role_name,
                    'role_code': role.role_code,
                    'permission_name': permission.permission_name,
                    'permission_code': permission.permission_code
                })
                items.append(data)
        
        return {
            'total': pagination.total,
            'page': page,
            'per_page': per_page,
            'items': items
        }

    @staticmethod
    def get_role_permission_by_id(id: int) -> Optional[RolePermission]:
        """
        根据ID获取角色权限关系
        :param id: 关系ID
        :return: 角色权限关系对象
        """
        return RolePermission.query.filter_by(id=id, deleted=False).first()

    @staticmethod
    def check_role_permission_exists(role_id: int, permission_id: int) -> bool:
        """
        检查角色权限关系是否存在
        :param role_id: 角色ID
        :param permission_id: 权限ID
        :return: 是否存在
        """
        return RolePermission.query.filter(
            and_(
                RolePermission.role_id == role_id,
                RolePermission.permission_id == permission_id,
                RolePermission.deleted == False
            )
        ).first() is not None

    @staticmethod
    def create_role_permission(role_id: int, permission_id: int) -> RolePermission:
        """
        创建角色权限关系
        :param role_id: 角色ID
        :param permission_id: 权限ID
        :return: 角色权限关系对象
        """
        role_permission = RolePermission(
            role_id=role_id,
            permission_id=permission_id
        )
        db.session.add(role_permission)
        db.session.commit()
        return role_permission

    @staticmethod
    def delete_role_permission(role_permission: RolePermission) -> bool:
        """
        删除角色权限关系（软删除）
        :param role_permission: 角色权限关系对象
        :return: 是否成功
        """
        role_permission.deleted = True
        role_permission.updated_at = datetime.now(timezone.utc)
        db.session.commit()
        return True

    @staticmethod
    def batch_update_role_permissions(role_id: int, permission_ids: List[int]) -> bool:
        """
        批量更新角色权限关系
        :param role_id: 角色ID
        :param permission_ids: 权限ID列表
        :return: 是否成功
        """
        try:
            # 先删除角色现有权限
            RolePermission.query.filter_by(role_id=role_id, deleted=False).update(
                {"deleted": True, "updated_at": datetime.now(timezone.utc)}
            )
            
            # 创建新的权限关系
            for permission_id in permission_ids:
                role_permission = RolePermission(role_id=role_id, permission_id=permission_id)
                db.session.add(role_permission)
            
            db.session.commit()
            return True
        except Exception:
            db.session.rollback()
            raise 